//
//  SingerTableViewController.m
//  K歌之王
//
//  Created by 小晓 on 16/1/3.
//  Copyright © 2016年 xiao. All rights reserved.
//

#import "SingerTableViewController.h"
#import "KMusicTableViewCell.h"
#import "KMusicDataModel.h"
#import "MusicClassTableViewCell.h"
#import "SingerHomeViewController.h"
#import "MusicAllAndAloneViewController.h"

@interface SingerTableViewController ()<UISearchBarDelegate>

@property (strong,nonatomic) NSMutableDictionary * singerDict;
@property (strong,nonatomic) NSMutableArray * songArray;

@end

@implementation SingerTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.titleName;
    _singerDict = [NSMutableDictionary dictionary];
    _songArray = [NSMutableArray array];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if([self.className isEqualToString:@"歌星点歌"]){
        [self requestHotSingerData];
        [self requestDataWithString:[NSString stringWithFormat:@"/api/singer_category/category_id/%@/singers",self.titleID]WithType:1];
    }else if([self.className isEqualToString:@"分类点歌"]){
        [self requestDataWithString:[NSString stringWithFormat:@"/api/songCategorys/category_id/%@/songs",self.titleID]WithType:2];
    }
}

-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.alpha = 1.0;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(backBtnAction)];
}

-(void)backBtnAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)requestDataWithString:(NSString *)urlStr WithType:(int)type{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:urlStr];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSDictionary * bodyDict = [dic objectForKey:@"body"];
        NSArray * contentArray = [bodyDict objectForKey:@"content"];
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        for(NSDictionary * contentDict in contentArray){
            if(type == 1){
                NSDictionary *singer = [contentDict objectForKey:@"singer"];
                NSString  *pingying;
                NSString  *seach=[singer[@"name"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                NSMutableString *str=[NSMutableString stringWithString:seach];
                CFStringTransform((__bridge CFMutableStringRef)str,nil,kCFStringTransformMandarinLatin, NO);
                //不带音标的
                CFStringTransform((__bridge CFMutableStringRef)str,nil,kCFStringTransformStripCombiningMarks, NO);
                pingying=[str uppercaseString];
                
                NSString *key = [pingying substringToIndex:1];
                NSMutableArray  *vlues=[dict objectForKey:key];
                if(vlues==nil) //如果不在则创建一个数组
                {
                    vlues=[NSMutableArray arrayWithCapacity:20];
                    [vlues addObject:singer[@"name"]];//将该联系人存入对应key的数组
                    [dict setObject:vlues forKey:key];
                }
                else
                {
                    [vlues addObject:singer[@"name"]]; //如果存则直接加入数组
                }
                
            }else if(type == 2){
                NSDictionary *song = [contentDict objectForKey:@"song"];
                HotMusicMsgDataModel * dataModel = [[HotMusicMsgDataModel alloc]init];
                dataModel.avatar = [song objectForKey:@"coverImage"];
                dataModel.size = [NSString stringWithFormat:@"%@",[song objectForKey:@"size"]];
                dataModel.name = [song objectForKey:@"name"];
                dataModel.singerName = [song objectForKey:@"singerName"];
                dataModel.lyric = [song objectForKey:@"lyric"];
                dataModel.accompanyUrl = [song objectForKey:@"accompanyUrl"];
                dataModel.url = [song objectForKey:@"url"];
                [dataModel fixedString];
                [_songArray addObject:dataModel];
            }
        }
        if(type == 1){
            NSArray * keys = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];
            for(NSString *key in keys){
                [_singerDict setObject:[dict objectForKey:key] forKey:key];
            }
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}

-(void)requestHotSingerData{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    NSString *intactURL = [MyBaseUrl stringByAppendingString:@"/api/singer/hot_tags"];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    //    创建请求
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSArray * bodyArray = [dic objectForKey:@"body"];
        [_singerDict setObject:bodyArray forKey:@"热门歌星"];
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    if([self.className isEqualToString:@"歌星点歌"]){
        return [[_singerDict allKeys] count];
    }else if([self.className isEqualToString:@"分类点歌"]){
        return 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if([self.className isEqualToString:@"歌星点歌"]){
        return [[_singerDict objectForKey:[[_singerDict allKeys] objectAtIndex:section]] count];
    }else if([self.className isEqualToString:@"分类点歌"]){
        return [_songArray count];
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    
    if([self.className isEqualToString:@"歌星点歌"]){
        cell = [tableView dequeueReusableCellWithIdentifier:@"singerMusicCell"];
        if(!cell){
            cell = [[MusicClassTableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"singerMusicCell"];
        }
        NSString *key = [[_singerDict allKeys]objectAtIndex:indexPath.section];
        NSString * dataStr = [[_singerDict objectForKey:key] objectAtIndex:indexPath.row];
        [((MusicClassTableViewCell *)cell) updataCellViewWithHeadData:dataStr Style:2];
    }else if([self.className isEqualToString:@"分类点歌"]){
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"KMusicTableViewCell"];
        if ( !cell ) {
            cell = [[KMusicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KMusicTableViewCell"];
        }
        [(KMusicTableViewCell *)cell updataCellViewWithHeadData:[_songArray objectAtIndex:indexPath.row]superViewCtr:self];
    }
    
    return cell;
}

#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.className isEqualToString:@"歌星点歌"]){
        SingerHomeViewController * singerHomeViewCtr = [[SingerHomeViewController alloc]init];
        NSString *key = [[_singerDict allKeys]objectAtIndex:indexPath.section];
        singerHomeViewCtr.titleName = [[_singerDict objectForKey:key] objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:singerHomeViewCtr animated:NO];
    }else{
        MusicAllAndAloneViewController *allAndAloneViewCtr = [MusicAllAndAloneViewController new];
        [self.navigationController pushViewController:allAndAloneViewCtr animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.className isEqualToString:@"歌星点歌"]){
        return 44;
    }else if([self.className isEqualToString:@"分类点歌"]){
        return 71;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([self.className isEqualToString:@"歌星点歌"]){
        return 20;
    }
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if([self.className isEqualToString:@"歌星点歌"]){
        NSString *dataStr = [[_singerDict allKeys]objectAtIndex:section];
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
        headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        UIView * fristView = [[UIView alloc]initWithFrame:CGRectMake(15, 5, 3, 10)];
        fristView.backgroundColor = [UIColor orangeColor];
        [headerView addSubview:fristView];
        UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(23, 5, 100, 10)];
        titleLabel.text = dataStr;
        titleLabel.textColor = [UIColor orangeColor];
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        [headerView addSubview:titleLabel];
        return headerView;
    }
    return nil;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if([self.className isEqualToString:@"歌星点歌"]){
        return [_singerDict allKeys];
    }
    return nil;
}

@end
